
class Promise2{
  state= "pending"
  callbacks = []
  
  constructor(fn:any){
    if(typeof fn !== "function"){
      throw new Error("promise 接收的是一个函数")
    }
    fn(this.resolve.bind(this),this.reject.bind(this))
  }

  resolve(value:any){
    setTimeout(()=>{
      if(this.state !== "pending"){return}
      this.state = "fulfilled"
      this.callbacks.forEach((handle)=>{
        if(typeof handle[0] === "function"){
          // @ts-ignore
          handle[0].call(undefined,value)
        }
      })
    },0)
  }
  reject(reason:any){
    setTimeout(()=>{
      if(this.state !== "pending"){return}
      this.state = "rejected"
      this.callbacks.forEach((handle)=>{
        if(typeof handle[1] === "function"){
          // @ts-ignore
          handle[1](reason)
        }
      })
    },0)
  }

  // @ts-ignore
  then(succeed?:any,fali?:any){
    // @ts-ignore
    const hande = []
    if(typeof succeed === "function"){
      hande[0] = succeed
    }
    if(typeof fali === "function"){
      hande[1] = fali
    }
    // @ts-ignore
    this.callbacks.push(hande)
  }

}
export default Promise2